package com.example.li_han.utils;

import java.sql.Connection;
import java.sql.*;

public class ConnUtils {
    //连接数据库
    public static  Connection getConn(){ //Connection是连接对象
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");//加载数据库的驱动类
            conn = DriverManager.getConnection(
                    //jdbc:mysql://主机IP：3306/数据库名?characterEncoding=UTF-8&serverTimezone=Asia&useSSL=false
                    "jdbc:mysql://10.47.164.207:3306/news?characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false",
                    "root",
                    "Sa123"
            );
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


        return  conn;
    }

    //关闭数据库
    public static void closeConnection(Connection conn){
        try {
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    // 在ConnUtils中添加
    public static void closeResources(Connection conn, PreparedStatement pst, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (pst != null) pst.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Connection conn =ConnUtils.getConn();
        if(conn!=null){
            System.out.println("连接成功");
        }else{
            System.out.println("连接失败");
        }
        ConnUtils.closeConnection(conn);

    }


}